package com.ly.emp.excelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ly.common.core.utils.excel.ExcelListener;
import com.ly.common.core.utils.excel.ExcelResult;
import com.ly.common.core.utils.SpringUtils;
import com.ly.emp.entity.EpmBaseSuitunit;
import com.ly.emp.service.IEpmBaseSuitunitService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 绩效考核单位-listener
 */
@Slf4j
public class EpmBaseSuitunitListener extends AnalysisEventListener<EpmBaseSuitunit> implements ExcelListener<EpmBaseSuitunit> {

    private final IEpmBaseSuitunitService service;
    private final Boolean isUpdateSupport;

    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();
    private int successNum = 0;
    private int failureNum = 0;
    private int startNum = 1;

    public EpmBaseSuitunitListener(Boolean isUpdateSupport) {
        this.service = SpringUtils.getBean(IEpmBaseSuitunitService.class);
        this.isUpdateSupport = isUpdateSupport;
    }

    @Override
    public void invoke(EpmBaseSuitunit entity, AnalysisContext context) {
        try {
            // 清空数据
            if (isUpdateSupport) {
                service.remove(new LambdaQueryWrapper<>());
            }
            service.saveOrUpdate(entity);
            successNum++;
        } catch (Exception e) {
            failureNum++;
            String msg = failureNum + "条数据导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }

    @Override
    public ExcelResult<EpmBaseSuitunit> getExcelResult() {
        return new ExcelResult<EpmBaseSuitunit>() {
            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "导入失败！共 " + failureNum + " 条数据导入失败，请检查！");
                    return failureMsg.toString();
                } else {
                    successMsg.insert(0, "导入成功！共 " + successNum + " 条数据已导入！");
                    return successMsg.toString();
                }
            }

            @Override
            public List<EpmBaseSuitunit> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
